import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { LocalStorage } from '@core/local.storage';
import { NzMessageService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';
declare const FullCalendar: any;

@Component({
    selector: 'app-calendar',
    templateUrl: './calendar.component.html',
    styleUrls: ['./workAreaWeave.component.less']
})
export class CalendarComponent implements OnInit {
    queryParams: any = {};
    workTypeSelect: any = [];
    upperTrackSelect: any = [];
    skyWindowSelect: any = [];
    operaData: any = {};
    detailVisible = false;
    addVisible = false;
    apiUrl: any = {};
    detail: any = {};
    tempData = '';

    queryList: any = [];
    wxlxTree = [];
    devNameSelect = [];
    personTree = [];

    operaList: any = [
        { addModal: false },
        { delModal: false }
    ];

    constructor(
        private http: _HttpClient,
        private router: Router,
        private datePipe: DatePipe,
        private msg: NzMessageService,
        private activatedRoute: ActivatedRoute,
        public ls: LocalStorage
    ) { }

    ngOnInit() {
        this.activatedRoute.queryParams.subscribe(param => {
            this.queryParams = param;
            this.apiUrl.add = environment.project + '/ymTWaweekplandkmn/add';
            this.apiUrl.edit = environment.project + '/ymTWaweekplandkmn/update';
            this.loadList();
        });
    }
    loadList() {
        this.http.get(environment.project + '/ymTWaweekplandkmn/wsquery?vcWsOrgId=' + this.queryParams.vcWsOrgId +
            '&vcYear=' + this.queryParams.vcYear +
            '&vcMonth=' + this.queryParams.vcMonth +
            '&vcWeeknum=' + this.queryParams.vcWeeknum).subscribe(res => {
                if (!res.code) {
                    this.queryList = res.data;
                    const array: any = [];
                    for (const item of res.data) {
                        array.push({
                            title: item.calTitle,
                            id: item.vcId,
                            date: this.datePipe.transform(item.dtWorkdate, 'yyyy-MM-dd'),
                            backgroundColor: item.vcWaId ? '#e0f0ff' : '#ffe0e0',
                            borderColor: item.vcWaId ? '#e0f0ff' : '#ffe0e0'
                        });
                    }
                    let thisDate: any;
                    thisDate = !array.length ? this.datePipe.transform(new Date(), 'yyyy-MM-dd') : array[0].date;
                    const calendarEl = document.getElementById('calendar');
                    const calendar = new FullCalendar.Calendar(calendarEl, {
                        headerToolbar: false,
                        editable: true,
                        firstDay: 0,
                        initialView: 'dayGridMonth',
                        initialDate: thisDate,
                        events: array,
                        locale: 'zh-cn',
                        weekends: true, // 日历面板中是否显示周末
                        selectable: true, // 日历中的日期是否可以被选中
                        selectOverlap: true, // 每个日期是否可以被重复选中多次
                        showNonCurrentDates: true, // 不是本月的日期是否需要在日历中显示
                        eventClick: (event) => {
                            this.dateClick(event);
                        },
                        select: (event) => {
                            this.addClick(event);
                        },
                        eventDrop: (event) => {
                            this.eventDrop(event);
                        }
                    });
                    calendar.render();
                }
            });
    }
    // handleDateSelect(selectInfo) {
    // 添加
    // const calendarApi = selectInfo.view.calendar;
    // calendarApi.unselect(); // clear date selection
    // calendarApi.addEvent({
    //     title: '选中',
    //     start: selectInfo.startStr,
    //     end: selectInfo.endStr,
    //     allDay: selectInfo.allDay
    // });
    // }
    limitDate(date, callback) {
        const start = new Date(this.queryParams.dtWeeksdate).getTime();
        const end = new Date(this.queryParams.dtWeekedate).getTime();
        const thisDate = new Date(date).getTime();
        let status = false;
        if (thisDate >= start && thisDate <= end) {
            status = true;
        }
        callback(status);
    }
    // 新增
    addClick(event) {
        // 根据状态值不能新增
        if (this.queryParams.typeName === 'workarea' && (this.queryParams.vcStatus === '2' || this.queryParams.vcStatus === '4')) {
            return;
        }
        if (this.queryParams.typeName === 'station' && (this.queryParams.vcStatus === '2' || this.queryParams.vcStatus === '4')) {
            return;
        }
        if (this.queryParams.typeName === 'seg') {
            return;
        }
        this.limitDate(event.startStr, (status) => {
            if (status) {
                this.tempData = event;
                this.modalShow('addModal');
            }
        });
    }
    // 修改
    dateClick(event) {
        this.limitDate(event.event.startStr, (status) => {
            // if (status) {
            this.http.get(environment.project + '/ymTWaweekplandkmn/query/' + event.event.id).subscribe(res => {
                if (!res.code) {
                    this.tempData = res.data[0];
                    switch (this.queryParams.vcStatus) {
                        case '1':
                            this.modalShow('editModal');
                            break;
                        case '5':
                            this.modalShow('editModal');
                            break;
                        default:
                            this.modalShow('viewModal');
                            break;
                    }
                }
            });
            // }
        });
        // 删除
        // clickInfo.event.remove();
    }
    eventDrop(event) {
        // 跨周若无周计划ID不可拖拽（因为数据无周计划ID暂时注销代码）
        // if (this.getWeek(event.oldEvent.startStr) !== this.getWeek(event.event.startStr)) {
        //     let vcWeekPlanId = '';
        //     for (const item of this.queryList) {
        //         if (item.vcId === Number(event.event.id)) {
        //             vcWeekPlanId = item.vcWeekPlanId;
        //             break;
        //         }
        //     }
        //     if (!vcWeekPlanId) {
        //         this.msg.error('没有选择周计划，请先创建');
        //         event.revert();
        //         return;
        //     }
        // }
        // 跨月不可拖拽
        if (this.datePipe.transform(event.oldEvent.startStr, 'MM') !== this.datePipe.transform(event.event.startStr, 'MM')) {
            this.msg.error('无法跨月拖动');
            event.revert();
            return;
        }
        // 根据状态值拖拽
        if (this.queryParams.typeName === 'seg') {
            event.revert();
            return;
        }
        if (this.queryParams.typeName === 'workarea' && this.queryParams.vcStatus !== '1' && this.queryParams.vcStatus !== '5') {
            event.revert();
            return;
        }
        if (this.queryParams.typeName === 'station' && this.queryParams.vcStatus !== '1' && this.queryParams.vcStatus !== '5') {
            event.revert();
            return;
        }
        this.limitDate(event.event.startStr, (status) => {
            if (status) {
                this.http.post(environment.project + '/ymTWaweekplandkmn/update', {
                    vcId: event.event.id,
                    dtWorkdate: event.event.startStr
                }).subscribe(res => {
                    if (res.code) {
                        event.revert();
                    }
                });
            } else {
                event.revert();
            }
        });
    }
    modalShow(type) {
        this.operaList[type] = true;
    }
    modalHide(type) {
        this.operaList[type] = false;
    }
    getWeek(dt) {
        const date = new Date(Number(dt.split('-')[0]), Number(dt.split('-')[1]) - 1, Number(dt.split('-')[2]))
        const w = date.getDay()
        const d = date.getDate()
        return Math.ceil((d + 6 - w) / 7)
    }
    back() {
        this.router.navigate(['workAreaWeave/' + this.queryParams.typeName]);
    }
}
